const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const { v4: uuidv4 } = require('uuid');
const Visitor = require('../models/Visitor');
const axios = require('axios');
require('dotenv').config();

// 头像列表
const avatars = [
    'https://www.knomi.me/aiImgas/tx1.png',
    'https://www.knomi.me/aiImgas/tx2.png',
    'https://www.knomi.me/aiImgas/tx3.png',
    'https://www.knomi.me/aiImgas/tx4.png',
    'https://www.knomi.me/aiImgas/tx5.png',
    'https://www.knomi.me/aiImgas/tx6.png',
    'https://www.knomi.me/aiImgas/tx7.png',
    'https://www.knomi.me/aiImgas/tx10.png'
];

// 随机获取头像URL
const getRandomAvatar = () => {
    const randomIndex = Math.floor(Math.random() * avatars.length);
    return avatars[randomIndex];
};

// 自定义函数处理令牌交换
async function exchangeCodeForToken(code) {
  try {
    const tokenResponse = await axios({
      method: 'post',
      url: 'https://oauth2.googleapis.com/token',
      headers: { 
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data: new URLSearchParams({
        code: code,
        client_id: process.env.GOOGLE_CLIENT_ID,
        client_secret: process.env.GOOGLE_CLIENT_SECRET,
        redirect_uri: process.env.GOOGLE_CALLBACK_URL,
        grant_type: 'authorization_code'
      }).toString(),
      timeout: 30000, // 增加超时时间
      maxRedirects: 5
    });
    
    return tokenResponse.data;
  } catch (error) {
    console.error('Token交换错误:', error.message);
    throw error;
  }
}

// 自定义函数获取用户信息
async function getUserProfile(accessToken) {
  try {
    const userInfoResponse = await axios({
      method: 'get',
      url: 'https://www.googleapis.com/oauth2/v2/userinfo',
      headers: {
        'Authorization': `Bearer ${accessToken}`
      },
      timeout: 30000
    });
    
    return userInfoResponse.data;
  } catch (error) {
    console.error('获取用户信息错误:', error.message);
    throw error;
  }
}

// Google OAuth策略配置
passport.use(new GoogleStrategy({
    clientID: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    callbackURL: process.env.GOOGLE_CALLBACK_URL,
    passReqToCallback: true
  },
  async (req, accessToken, refreshToken, profile, done) => {
    try {
      // 检查visitor是否已通过Google账号存在
      let visitor = await Visitor.findOne({
        where: { googleId: profile.id }
      });

      // 如果访客存在，返回访客信息
      if (visitor) {
        // 更新最后登录时间和登录次数
        await visitor.update({
          last_login: new Date(),
          login_count: visitor.login_count + 1
        });
        return done(null, visitor);
      }

      // 随机分配头像
      const avatar = getRandomAvatar();

      // 如果访客不存在，创建新访客
      visitor = await Visitor.create({
        uuid: uuidv4(),
        googleId: profile.id,
        email: profile.emails[0].value,
        displayName: profile.displayName,
        avatar: avatar,
        last_login: new Date(),
        status: 'active'
      });

      return done(null, visitor);
    } catch (error) {
      return done(error, false);
    }
  }
));

// 序列化用户，保存到session
passport.serializeUser((visitor, done) => {
  done(null, visitor.uuid);
});

// 反序列化用户，从session恢复用户
passport.deserializeUser(async (uuid, done) => {
  try {
    const visitor = await Visitor.findByPk(uuid);
    done(null, visitor);
  } catch (error) {
    done(error, null);
  }
});

module.exports = passport; 